import 'package:flutter/material.dart';
import '../../utils/easy_throttle.dart';

class AppButton extends ElevatedButton {
  AppButton({
    super.key,
    required super.child,
    void Function()? onTap,
    bool enable = true,
    bool isLoading = false,
    Widget? loadingWidget,

    // 颜色
    Color? backgroundColor,
    Color? disableBackgroundColor,
    Color? foregroundColor,
    Color? disableForegroundColor,

    // 尺寸
    double? width,
    double? height,
    EdgeInsetsGeometry? padding,

    // 样式
    BorderRadius? borderRadius,
    BorderSide? side,
    BorderSide? disableSide,
    double? elevation,

    // 防抖
    bool throttle = true,
    Duration? throttleDuration,
  }) : super(
         onPressed: _buildOnPressed(enable, isLoading, onTap, throttle, throttleDuration),
         style: _buildStyle(
           backgroundColor: backgroundColor,
           disableBackgroundColor: disableBackgroundColor,
           foregroundColor: foregroundColor,
           disableForegroundColor: disableForegroundColor,
           enable: enable,
           isLoading: isLoading,
           width: width,
           height: height,
           padding: padding,
           borderRadius: borderRadius,
           side: side,
           disableSide: disableSide,
           elevation: elevation,
         ),
       );

  /// ==================== 工厂构造函数 ====================

  /// 文本按钮
  factory AppButton.text({
    required String text,
    void Function()? onTap,
    TextStyle? style,
    bool enable = true,
    bool isLoading = false,
    Widget? loadingWidget,
    Color backgroundColor = Colors.transparent,
    Color? disableBackgroundColor,
    Color? foregroundColor,
    Color? disableForegroundColor,
    double? width,
    double? height,
    EdgeInsetsGeometry? padding,
    BorderRadius? borderRadius,
    BorderSide? side,
    BorderSide? disableSide,
    double? elevation,
    bool throttle = true,
    Duration? throttleDuration,
  }) {
    return AppButton(
      onTap: onTap,
      enable: enable,
      isLoading: isLoading,
      loadingWidget: loadingWidget,
      backgroundColor: backgroundColor,
      disableBackgroundColor: disableBackgroundColor,
      foregroundColor: foregroundColor,
      disableForegroundColor: disableForegroundColor,
      width: width,
      height: height,
      padding: padding,
      borderRadius: borderRadius,
      side: side,
      disableSide: disableSide,
      elevation: elevation,
      throttle: throttle,
      throttleDuration: throttleDuration,
      child: _buildTextChild(
        text: text,
        style: style,
        foregroundColor: foregroundColor,
        disableForegroundColor: disableForegroundColor,
        enable: enable,
        isLoading: isLoading,
        loadingWidget: loadingWidget,
      ),
    );
  }

  /// 图标+文本按钮
  factory AppButton.icon({
    required IconData icon,
    required String text,
    void Function()? onTap,
    TextStyle? style,
    bool enable = true,
    bool isLoading = false,
    Widget? loadingWidget,
    Color? backgroundColor,
    Color? disableBackgroundColor,
    Color? foregroundColor,
    Color? disableForegroundColor,
    double? width,
    double? height,
    EdgeInsetsGeometry? padding,
    BorderRadius? borderRadius,
    BorderSide? side,
    BorderSide? disableSide,
    double? elevation,
    bool throttle = true,
    Duration? throttleDuration,
    double iconSize = 20,
    double iconSpacing = 8,
  }) {
    return AppButton(
      onTap: onTap,
      enable: enable,
      isLoading: isLoading,
      loadingWidget: loadingWidget,
      backgroundColor: backgroundColor,
      disableBackgroundColor: disableBackgroundColor,
      foregroundColor: foregroundColor,
      disableForegroundColor: disableForegroundColor,
      width: width,
      height: height,
      padding: padding,
      borderRadius: borderRadius,
      side: side,
      disableSide: disableSide,
      elevation: elevation,
      throttle: throttle,
      throttleDuration: throttleDuration,
      child: _buildIconTextChild(
        icon: icon,
        text: text,
        style: style,
        foregroundColor: foregroundColor,
        disableForegroundColor: disableForegroundColor,
        enable: enable,
        isLoading: isLoading,
        loadingWidget: loadingWidget,
        iconSize: iconSize,
        iconSpacing: iconSpacing,
      ),
    );
  }

  // ==================== 私有方法 ====================

  static void Function()? _buildOnPressed(bool enable, bool isLoading, void Function()? onTap, bool throttle, Duration? throttleDuration) {
    if (!enable || isLoading || onTap == null) return null;
    if (throttle) {
      return EasyThrottle.tapThrottle(onTap, duration: throttleDuration);
    }
    return onTap;
  }

  static ButtonStyle _buildStyle({
    Color? backgroundColor,
    Color? disableBackgroundColor,
    Color? foregroundColor,
    Color? disableForegroundColor,
    required bool enable,
    required bool isLoading,
    double? width,
    double? height,
    EdgeInsetsGeometry? padding,
    BorderRadius? borderRadius,
    BorderSide? side,
    BorderSide? disableSide,
    double? elevation,
  }) {
    return ButtonStyle(
      backgroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
        if (states.contains(WidgetState.disabled)) {
          return disableBackgroundColor ?? backgroundColor?.withOpacity(0.5);
        }
        return backgroundColor;
      }),
      foregroundColor: WidgetStateProperty.resolveWith<Color?>((states) {
        if (states.contains(WidgetState.disabled)) {
          return disableForegroundColor ?? foregroundColor?.withOpacity(0.5);
        }
        return foregroundColor;
      }),
      minimumSize: WidgetStateProperty.all(Size(width ?? double.infinity, height ?? 56)),
      padding: WidgetStateProperty.all(padding ?? EdgeInsets.zero),
      shape: WidgetStateProperty.all(
        RoundedRectangleBorder(
          borderRadius: borderRadius ?? BorderRadius.circular(12),
          side: ((!enable || isLoading) ? (disableSide ?? side) : side) ?? BorderSide.none,
        ),
      ),
      elevation: WidgetStateProperty.all(elevation ?? 0),
      splashFactory: NoSplash.splashFactory,
    );
  }

  static Widget _buildTextChild({
    required String text,
    TextStyle? style,
    Color? foregroundColor,
    Color? disableForegroundColor,
    required bool enable,
    required bool isLoading,
    Widget? loadingWidget,
  }) {
    if (isLoading) {
      return loadingWidget ??
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation<Color>(foregroundColor ?? Colors.white)),
              ),
              SizedBox(width: 8),
              Text(text, style: style),
            ],
          );
    }

    final effectiveColor = !enable ? disableForegroundColor : foregroundColor;

    return Text(text, style: style?.copyWith(color: effectiveColor) ?? TextStyle(color: effectiveColor));
  }

  static Widget _buildIconTextChild({
    required IconData icon,
    required String text,
    TextStyle? style,
    Color? foregroundColor,
    Color? disableForegroundColor,
    required bool enable,
    required bool isLoading,
    Widget? loadingWidget,
    required double iconSize,
    required double iconSpacing,
  }) {
    if (isLoading) {
      return loadingWidget ??
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation<Color>(foregroundColor ?? Colors.white)),
              ),
              SizedBox(width: 8),
              Icon(icon, size: iconSize),
              SizedBox(width: iconSpacing),
              Text(text, style: style),
            ],
          );
    }

    final effectiveColor = !enable ? disableForegroundColor : foregroundColor;

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: iconSize, color: effectiveColor),
        SizedBox(width: iconSpacing),
        Text(text, style: style?.copyWith(color: effectiveColor) ?? TextStyle(color: effectiveColor)),
      ],
    );
  }
}

// 1. 基础文本按钮
// AppButton.text(
// '登录',
// onTap: () => print('登录'),
// backgroundColor: Colors.blue,
// foregroundColor: Colors.white,
// )
//
// // 2. 禁用状态（自动降透明度）
// AppButton.text(
// '提交',
// onTap: () => print('提交'),
// enable: false,
// backgroundColor: Colors.blue,
// foregroundColor: Colors.white,
// )
//
// // 3. 自定义禁用颜色
// AppButton.text(
// '删除',
// onTap: () => print('删除'),
// enable: false,
// backgroundColor: Colors.red,
// foregroundColor: Colors.white,
// disableBackgroundColor: Colors.red.withOpacity(0.4),
// disableForegroundColor: Colors.white70,
// )
//
// // 4. 图标按钮
// AppButton.icon(
// Icons.add,
// '添加设备',
// onTap: () => print('添加'),
// backgroundColor: Colors.green,
// foregroundColor: Colors.white,
// )
//
// // 5. 加载状态
// AppButton.text(
// '提交中...',
// onTap: () => print('提交'),
// isLoading: true,
// backgroundColor: Colors.blue,
// foregroundColor: Colors.white,
// )
//
// // 6. 自定义加载组件
// AppButton.text(
// '上传',
// onTap: () => print('上传'),
// isLoading: true,
// loadingWidget: Row(
// mainAxisSize: MainAxisSize.min,
// children: [
// SizedBox(
// width: 12,
// height: 12,
// child: CircularProgressIndicator(strokeWidth: 1),
// ),
// SizedBox(width: 4),
// Text('上传中...', style: TextStyle(fontSize: 12)),
// ],
// ),
// )
